﻿using System;
using Eneta.Portal.Common;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace Eneta.Portal.NewsAndBlogs
{
    public class CommentListFeatureReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            var web = properties.Feature.Parent as SPWeb;
            if (web == null)
                web = ((SPSite)properties.Feature.Parent).RootWeb;

            if (!PublishingWeb.IsPublishingWeb(web))
                throw new Exception("Current web is not publishing web!");

            web.AllowUnsafeUpdates = true;

            var pagesListName = PublishingWeb.GetPagesListName(web);
            var pagesList = web.Lists[pagesListName];
            var list = web.Lists["Comments"];

            if (list.HasField("NewsItem"))
                return;

            list.Fields.AddLookup("NewsItem", pagesList.ID, true);
            var field = list.Fields["NewsItem"] as SPFieldLookup;
            field.LookupField = pagesList.Fields[SPBuiltInFieldId.Title].InternalName;
            field.Update(true);
            list.Update();
        }
    }
}
